<?php
namespace app\service;
use app\model\AdminModel;
use think\facade\Db;
class AiService
{
    private static function curl($url,$data,$auth_token,$stream,$feedback=''){
        $ch = curl_init();
        $headers = ['Content-Type: application/json','Authorization: Bearer '.$auth_token];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        if($stream){
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 不返回结果，直接输出
            if (!empty($data)) {
                $data['stream']=true;
                $params[CURLOPT_POST] = true;
                $params[CURLOPT_POSTFIELDS] = \json_encode($data);
            }
            curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) use (&$receivedData,$feedback) {
                $feedback($data);
                return strlen($data);
            });
        }else{
            $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
            if (!empty($data)) {
                $params[CURLOPT_POST] = true;
                $params[CURLOPT_POSTFIELDS] = \json_encode($data);
            }
        }
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        if(json_decode($content, true)){
            return json_decode($content, true);
        }
        return $content;
    }
    public static function zhipuAIv4($message=[],$stream=false,$feedback=''){
        $zhipu_config=config('ai.zhipu');
        $data=$zhipu_config['data'];
        $data['messages']=$message;
        return self::curl($zhipu_config['url'],$data,$zhipu_config['auth_token'],$stream,$feedback);
    }

    public static function xinghuoLite($message=[],$stream=false,$feedback=''){
        $xinghuo_config=config('ai.xinghuo');
        $data=$xinghuo_config['data'];
        $data['messages']=$message;
        return self::curl($xinghuo_config['url'],$data,$xinghuo_config['auth_token'],$stream,$feedback);
    }


}